#include "stdafx.h"
#include "AudioManager.h"
#include "SoundEffect2D.h"
#include "SoundEffect3D.h"
#include "ISoundElement.h"
#include "SoundEffect2D.h"
#include "SoundEffect3D.h"
#include <assert.h>
#include <fmod_common.h>
#include <fmod_output.h>

AudioManager::AudioManager(void)
{
	FMOD_RESULT fr = FMOD::System_Create(&fmod_system);
	assert(SUCCEEDED(fr) && "failed to initalize fmod");

	fmod_system->init(32, FMOD_INIT_NORMAL, 0);
}

void AudioManager::setMasterVolume(float value) 
{
}

/*static*/ AudioManager* AudioManager::GetInstance(void)
{
	static AudioManager instance;

	return &instance;
}


AudioManager::~AudioManager(void)
{
	fmod_system->release();
}

SoundEffect3D*  AudioManager::CreateSound3D(const char* filename)
{
	FMOD::Sound* sound;
	FMOD_RESULT	fr = fmod_system->createSound(filename, FMOD_3D, nullptr, &sound);

	SoundEffect3D* outval = new SoundEffect3D;
	outval->sound = sound;

	return outval;
}

SoundEffect2D*  AudioManager::CreateSound2D(const char* filename)
{
	FMOD::Sound* sound;
	FMOD_RESULT	fr = fmod_system->createSound(filename, FMOD_2D, nullptr, &sound);

	SoundEffect2D* outval = new SoundEffect2D;
	outval->sound = sound;

	return outval;
}

void AudioManager::PlaySound(ISoundElement* sound)
{
	FMOD::Channel* channel;
	fmod_system->playSound(sound->getSound(), nullptr, false, &channel);
	
	sound->setChannel(channel);
}

void AudioManager::StopSound(ISoundElement* sound)
{
}

void AudioManager::PauseSound(ISoundElement* sound)
{
}

float AudioManager::getMasterVolume(void) const
{
	return 100.f;
}

void AudioManager::Update(void)
{
	for (unsigned int i = 0; i < activeElements.size(); i++)
		activeElements[i]->Update();
	
	fmod_system->set3DListenerAttributes(0, makeFmodVector(worldListenPosition), nullptr, nullptr, nullptr);
	fmod_system->update();
}